package dk.aiszone.lang.sql;

import static dk.aiszone.lang.sql.SQLHelper.escapeReservedWord;
import dk.aiszone.lang.sql.interfaces.SQLObject;
import dk.aiszone.lang.sql.interfaces.SQLPart;

/**
 * <code>SQLObject</code> representing a field select in a SQL clause.
 * 
 * @author ads
 */
public class SQLField extends AbstractSQLObject implements SQLObject, SQLPart {

    private final String alias;
    private final String fieldName;
    private SQLTable parent;

    /**
     * Constructor for the <code>SQLField</code>.
     * 
     * @param field
     *            The name of the field.
     */
    public SQLField(String field) {
        this(field, null);
    }

    /**
     * Constructor for the <code>SQLField</code>.
     * 
     * @param field
     *            The name of the field.
     * @param alias
     *            <b>Optionally</b> The alias of the field.
     */
    public SQLField(String field, String alias) {
        this.fieldName = field;
        this.alias = alias;
    }

    @Override
    public SQLResult prepareSQL(SQLResult sql) {
        return sql.append(getFormattedName());
    }

    @Override
    public String toPreparedStatement() {
        return toSQL();
    };

    public String toSQL() {
        return getFormattedName();
    }

    /* pp */String getAlias() {
        return alias;
    }

    /* pp */String getFormattedName() {
        StringBuilder sql = new StringBuilder();
        if (parent != null) {
            sql.append(parent.getAlias() != null ? parent.getAlias() : parent.getTableName()).append(".");
        }
        sql.append(escapeReservedWord(fieldName));

        if (alias != null) {
            sql.append(" AS ");

            sql.append(escapeReservedWord(alias));
        }
        return sql.toString();
    }

    /* pp */String getName() {
        return fieldName;
    }

    /* pp */SQLTable getParent() {
        return parent;
    }

    /* pp */void setParent(SQLTable parent) {
        this.parent = parent;
    }

}